<script setup lang="ts">
import dayjs from 'dayjs';
import { reLaunch, showToast, showModal, showLoading, hideLoading } from '@tarojs/taro';
import ARCHIVE_TYPE_FOLDER from '/@/assets/image/icon/archive-type-folder.png';
import {
  UPDATE_DOSSIER,
  INSERT_DOSSIER,
  DELETE_DOSSIER,
  UPDATE_DOSSIER_TYPE,
  INSERT_DOSSIER_TYPE,
  DELETE_DOSSIER_TYPE,
} from '/@/api/modules/archive/police/dossier-manager';
import { state as newState } from './state';
import { state } from '/@/common/hooks/state';
import { Search2 as NutIconSearch2 } from '@nutui/icons-vue-taro';
import { ARCHIVE_FILE_TYPE, ARCHIVE_FILE_TYPE_BY_SUFFIX } from '/@/common/constant';
import { getFileSize, archiveUploadFile } from '/@/utils/file';
import { getSysImgUrl } from '/@/utils/index';
import { back } from '/@/utils/back';
import useArchiveList from '/@/common/hooks/archive-list';

const { next, navigation, openFile, refreshList } = useArchiveList();

/**
 * 重命名文件夹
 */
function renameFolder(id?: string, name?: string) {
  newState.renameFolderId = id || '';
  newState.nameFolder = name || '';
  newState.renameFolderDialogVisible = true;
}

/**
 * 删除文件夹
 */
function removeFolder(id?: string) {
  showModal({
    title: '删除文件夹',
    content: '确认删除文件夹？',
    success: (res) => {
      if (!res.confirm) return;
      showLoading({ title: '加载中...' });
      DELETE_DOSSIER_TYPE({
        ids: [id || ''],
      }).then((res) => {
        if (res.comResp.code === 100) {
          refreshList();
        }
      });
    },
  });
}

/**
 * 重命名文件
 */
function renameFile(item: DossierManager.fileDto) {
  newState.renameFileItem = item;
  newState.renameFileDialogVisible = true;
}

/**
 * 删除文件
 */
function removeFile(id?: string) {
  showModal({
    title: '删除文件',
    content: '确认删除文件？',
    success: (res) => {
      if (!res.confirm) return;
      showLoading({ title: '加载中...' });
      DELETE_DOSSIER({
        ids: [id || ''],
      }).then((res) => {
        if (res.comResp.code === 100) {
          refreshList();
        }
      });
    },
  });
}

/**
 * 上传文档 点击事件
 */
function uploadDocument() {
  const inputParent = document.getElementById('uploadFileId');
  if (!inputParent) {
    return;
  }
  const input = inputParent.children[0] as HTMLInputElement;
  if (!input) {
    return;
  }

  input.click();
}

/**
 * 新建文件夹
 */
function newFolder() {
  newState.createFolderName = '';
  newState.createFolderDialogVisible = true;
}

/**
 * 重命名文件夹对话框确认
 */
function renameFolderConfirm() {
  if (!newState.nameFolder) {
    showToast({ title: '请输入文件夹名称', icon: 'error' });
    return;
  }
  UPDATE_DOSSIER_TYPE({
    content: {
      id: newState.renameFolderId,
      dossierTypeName: newState.nameFolder,
    },
  }).then((res) => {
    if (res.comResp.code === 100) {
      refreshList();
    }
  });
}

/**
 * 创建文件夹对话框确认
 */
function createFolderConfirm() {
  if (!newState.createFolderName) {
    showToast({ title: '请输入文件夹名称', icon: 'error' });
    return;
  }
  showLoading();
  INSERT_DOSSIER_TYPE({
    content: {
      parentId: state.dossierTypeId,
      dossierTypeName: newState.createFolderName,
    },
  }).then((res) => {
    if (res.comResp.code === 100) {
      refreshList();
    }
  });
}

/**
 * 重新命名文件-确认
 */
function renameFileConfirm() {
  if (!newState.renameFileItem.name) {
    showToast({ title: '请输入文件名称', icon: 'error' });
    return;
  }
  showLoading();
  UPDATE_DOSSIER({
    content: {
      ...newState.renameFileItem,
    },
  }).then((res) => {
    if (res.comResp.code === 100) {
      refreshList();
    }
  });
}

/**
 * 改变文件状态-禁用/启用
 * @param item
 */
function changeFileStatus(item: DossierManager.fileDto) {
  const title = '修改文件状态';
  let content = '';
  if (item.flag === 1) {
    content = '禁用后用户将无法查看、借阅该文档，确定禁用吗？';
  } else {
    content = '启用后用户可继续查看、借阅该文档​，确定启用吗？​';
  }

  showModal({
    title,
    content,
    success: (res) => {
      if (!res.confirm) return;
      if (item.flag === 1) {
        item.flag = 2;
      } else {
        item.flag = 1;
      }
      showLoading({ title: '加载中...' });
      UPDATE_DOSSIER({
        content: {
          ...item,
        },
      }).then((res) => {
        if (res.comResp.code === 100) {
          refreshList();
        }
      });
    },
  });
}

function changeUploadFile(e: any) {
  const file: File = e.target.children[0].files[0];
  archiveUploadFile(file, addArchive);
  //置空
  e.target.children[0].value = '';
}
/**
 *  新增档案
 * @param uploadFileName 上传文件名
 * @param fileSuffix 文件后缀
 * @param url 上传文件后的url地址
 * @param fileSize 文件大小
 */
function addArchive(uploadFileName: string, fileSuffix: string, url: string, fileSize: number) {
  //当前的档案目录
  const currentItem = state.selectedTypeList[state.selectedTypeList.length - 1];
  INSERT_DOSSIER({
    content: {
      typeId: currentItem.id || '',
      typeCode: currentItem.dossierTypeCode || '',
      typeName: currentItem.dossierTypeName || '',
      name: uploadFileName,
      url,
      category: ARCHIVE_FILE_TYPE_BY_SUFFIX[fileSuffix],
      memory: getFileSize(fileSize),
      enable: 1,
      flag: 1,
    },
  }).then((res) => {
    hideLoading();
    if (res.comResp.code === 100) {
      refreshList();
    } else {
      showToast({ title: '添加档案错误', icon: 'error' });
    }
  });
}
</script>

<template>
  <view class="archive-manage-list app-page--1">
    <app-navbar title="档案管理" @handleBack="back()" :hookBack="true" />
    <nut-tabs
      model-value="list"
      @click="
        ({ paneKey }) => {
          if (paneKey === 'statistics') {
            reLaunch({ url: '/pages/archive-manage-new/statistics/index' });
          }
        }
      "
    >
      <nut-tab-pane title="档案管理" pane-key="list" />
      <nut-tab-pane title="统计分析" pane-key="statistics" />
    </nut-tabs>
    <nut-searchbar v-model="state.keywords" placeholder="请输入档案名称" @search="refreshList">
      <template v-slot:leftin>
        <nut-icon-search2 />
      </template>
    </nut-searchbar>
    <scroll-view
      class="horizontal-scroll-view"
      :scroll-x="true"
      :lower-threshold="100"
      :scroll-with-animation="true"
      :scroll-left="state.scrollLeft"
      id="scroll_view_container"
    >
      <view
        v-for="(item, index) in state.selectedTypeList"
        :key="item.id"
        class="archive-manage-list__navigation-item"
        @click="navigation(index)"
      >
        <text :style="{ color: index === state.selectedTypeList.length - 1 ? '#333' : '#507aee' }"
          >{{ item.dossierTypeName
          }}{{ index != state.selectedTypeList.length - 1 ? '>' : '' }}</text
        >
      </view>
    </scroll-view>
    <scroll-view class="app-page__wrapper" :scroll-y="true" :lower-threshold="100">
      <view class="archive-manage-list__wrapper">
        <nut-cell-group>
          <nut-cell v-for="item in state.typeList" :key="item.id" @click="next(item)">
            <template v-slot:title>
              <view class="archive-manage-list__left">
                <view>
                  <nut-avatar size="small" shape="square">
                    <image :src="ARCHIVE_TYPE_FOLDER" />
                  </nut-avatar>
                </view>
                <view>
                  <view class="archive-manage-list__title">
                    <text>{{ item.dossierTypeName || '' }}</text>
                  </view>
                  <view class="archive-manage-list__count">
                    <text>文档:&nbsp;&nbsp;{{ item.num || 0 }}</text>
                  </view>
                </view>
              </view>
            </template>
            <template v-slot:link>
              <view class="archive-manage-list__right">
                <view
                  class="archive-manage-list__rename"
                  @click.stop="renameFolder(item.id, item.dossierTypeName)"
                >
                  <text>重命名</text>
                </view>
                <view @click.stop="removeFolder(item.id)">
                  <text>删除</text>
                </view>
              </view>
            </template>
          </nut-cell>
        </nut-cell-group>

        <nut-cell-group>
          <nut-cell v-for="item in state.dtoList" :key="item.id" @click="openFile(item)">
            <template v-slot:title>
              <view class="archive-manage-list__left">
                <view>
                  <nut-avatar size="small" shape="square">
                    <image :src="ARCHIVE_FILE_TYPE[item.category || 9]" />
                  </nut-avatar>
                </view>
                <view>
                  <view class="archive-manage-list__title">
                    <text>{{ item.name || '' }}</text>
                  </view>
                  <view class="archive-manage-list__count">
                    <text
                      >{{ item.memory || '' }}&nbsp;&nbsp;上传时间:&nbsp;{{
                        dayjs(item.uploadTime).format('YYYY-MM-DD HH:mm')
                      }}</text
                    >
                  </view>
                </view>
              </view>
            </template>
            <template v-slot:link>
              <view class="archive-manage-list__right">
                <view class="archive-manage-list__rename" @click.stop="renameFile(item)">
                  <text>重命名</text>
                </view>
                <view
                  class="archive-manage-list__disable"
                  @click.stop="changeFileStatus(item)"
                  v-if="item.flag === 1"
                >
                  <text>禁用</text>
                </view>
                <view
                  class="archive-manage-list__enable"
                  @click.stop="changeFileStatus(item)"
                  v-else
                >
                  <text>启用</text>
                </view>
                <view @click.stop="removeFile(item.id)">
                  <text>删除</text>
                </view>
              </view>
            </template>
          </nut-cell>
        </nut-cell-group>
      </view>
    </scroll-view>
    <view class="archive-manage-list__footer">
      <nut-button class="archive-manage-list__footer-btn" type="info" @click="uploadDocument()"
        >上传文档</nut-button
      >
      <nut-button class="archive-manage-list__footer-btn" type="info" @click="newFolder()"
        >新建文件夹</nut-button
      >
    </view>
    <input
      id="uploadFileId"
      type="file"
      name="file"
      accept="image/*"
      @change="changeUploadFile"
      class="archive-manage-list__upload-file"
    />

    <nut-dialog
      title="重新命名文件夹"
      v-model:visible="newState.renameFolderDialogVisible"
      @ok="renameFolderConfirm"
    >
      <template v-slot:default>
        <view>
          <view>
            <nut-avatar size="large" shape="square">
              <image :src="ARCHIVE_TYPE_FOLDER" />
            </nut-avatar>
          </view>
          <view>
            <nut-input
              v-model="newState.nameFolder"
              placeholder="请输入新文件夹名"
              clearable
              clearSize="14"
            />
          </view>
        </view>
      </template>
    </nut-dialog>

    <nut-dialog
      title="新建文件夹"
      v-model:visible="newState.createFolderDialogVisible"
      @ok="createFolderConfirm"
    >
      <template v-slot:default>
        <view>
          <view>
            <nut-avatar size="large" shape="square">
              <image :src="ARCHIVE_TYPE_FOLDER" />
            </nut-avatar>
          </view>
          <view>
            <nut-input
              v-model="newState.createFolderName"
              placeholder="请输入新文件夹名"
              clearable
              clearSize="14"
            />
          </view>
        </view>
      </template>
    </nut-dialog>

    <nut-dialog
      title="重新命名文件"
      v-model:visible="newState.renameFileDialogVisible"
      @ok="renameFileConfirm"
    >
      <template v-slot:default>
        <view>
          <view>
            <nut-avatar size="large" shape="square">
              <image :src="ARCHIVE_FILE_TYPE[newState.renameFileItem.category || 9]" />
            </nut-avatar>
          </view>
          <view>
            <nut-input
              v-model="newState.renameFileItem.name"
              placeholder="请输入新文件名"
              clearable
              clearSize="14"
            />
          </view>
        </view>
      </template>
    </nut-dialog>
    <nut-image-preview
      :show="state.showImagePreview"
      :images="
        state.imageList.map((url) => {
          return { src: getSysImgUrl(url) };
        })
      "
      @close="
        () => {
          state.showImagePreview = false;
        }
      "
    />
  </view>
</template>

<style lang="scss">
@import './index.scss';
</style>
../../../common/hooks/state../../../common/hooks/archive-list
